<?php
//**************************************************************************
//
//            (C) Okulov Rostislav, 2011
//
//**************************************************************************

/*
 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.        *
 *                                                                         *
 */

   include ('mysql_connect.php');
   include ('func_list.php');

   // Подключаемся к mysql серверу
   $link = mysql_connect($dbhost, $dbuser, $dbpassword);
   if (empty($link)) {
      echo 'Не удалось подключиться к MySQL'; 
      exit;
   }
   // Выбираем нашу базу данных
   mysql_select_db($dbname, $link);
?>
   <div style="border: 1px dotted;"><span>Сайт предназначен для новичков в мире операционных систем GNU/Linux и создании сайтов.</span>
   </div>
   <h4>Новости/Заметки</h4>
<?php
    if (isset($_GET['submit_reg_comment'])) {
       $phpdate = $_SERVER['REQUEST_TIME'];
       $mysqldate = date('Y-m-d H:i:s', $phpdate);
       $query = "INSERT INTO comments VALUES (0,'".mysql_escape_string($_SESSION['user'])."','".mysql_escape_string(strip_tags($_GET['user_comment']))."','".mysql_escape_string($_GET['article_id'])."',-1,'".mysql_escape_string($mysqldate)."')";
       mysql_query($query, $link);
    }

    if (isset($_POST['submit_comment'])) {
       if (preg_match('/^[a-z0-9]{4,20}$/i',$_POST['user_name']) &&  preg_match('/^[a-z0-9]{4,20}$/i',$_POST['user_pass'])) {
          if ($_POST['user_name'] == 'anonymous' && $_POST['user_pass'] == 'aaaaaa') {
             if ($_SESSION['key'] != md5($_POST['cfiled'])) {
                echo "Не получилось!";
                exit;
             }
             else
             {
                $phpdate = $_SERVER['REQUEST_TIME'];
                $mysqldate = date('Y-m-d H:i:s', $phpdate);
                $query = "INSERT INTO comments VALUES (0,'".mysql_escape_string($_POST['user_name'])."','".mysql_escape_string(strip_tags($_POST['user_comment']))."','".mysql_escape_string($_POST['article_id'])."',-1,'".mysql_escape_string($mysqldate)."')";
                mysql_query($query, $link);
             }
      
          }
       }
       else {
     if ( (isset($_POST['user_name'])) && (isset($_POST['user_pass'])) ) {
         if (preg_match('/^[a-z0-9]{4,20}$/i',$_POST['user_name'])) {
           $login = $_POST['user_name'];     
           $query = "SELECT id, pass FROM users WHERE login='".mysql_escape_string($login)."'";
           $result = mysql_query($query);
           if (mysql_num_rows($result) > 0) {
              $userinfo = mysql_fetch_array($result);
              if (preg_match('/^[a-z0-9]{4,11}$/i',$_POST['user_pass'])) {
                 $pass = $_POST['user_pass'];
                 if (md5($pass) == $userinfo['pass']){
                    $query = "SELECT * FROM users WHERE login='".mysql_escape_string($login)."'";
                    $result = mysql_query($query);
                    $userinfo = mysql_fetch_array($result);
                    $time = time();
                    $_SESSION['user'] = $login;
                    $_SESSION['email'] = $userinfo['email'];
                    $_SESSION['sessid'] = session_id();
                    setcookie("l_login", $login, $time+50000);
                    setcookie("l_pass", md5($pass), $time+50000);
                    $state = 1;
                    $phpdate = $_SERVER['REQUEST_TIME'];
                    $mysqldate = date('Y-m-d H:i:s', $phpdate);
                    $query = "INSERT INTO comments VALUES (0,'".mysql_escape_string($_SESSION['user'])."','".mysql_escape_string(strip_tags($_POST['user_comment']))."','".mysql_escape_string($_POST['article_id'])."',-1,'".mysql_escape_string($mysqldate)."')";
                    mysql_query($query, $link);
                 }
              }
           }
        }
  
      }


      }
    } // end $_POST['submit_comment']
    if (isset($_GET['artid'])) {
       $query = "SELECT * FROM `mynews` WHERE id='".intval($_GET['artid'])."' AND approved='1'";
       $result = mysql_query($query, $link);
       if (mysql_num_rows($result) != 0){
       $approved = 1;
           while ($line = mysql_fetch_array($result)) {
                 echo '<div class="sidebar"><div style="float:top;">';
                 echo '<span style="color:rgb(237, 106, 52);">'.$line["n_author"].' | <span style="color:blue;">'.$line["title"].'</span></span><br /><span style="font-size:70%;">'.$line["n_time"].'</span>';
                 echo '</div><p>';
                 echo '<span>'.preg_replace("/(-){2,}/", '', bbcode($line["newstext"])).'</span>';
                 echo '</p>';
                 echo 'Метки: ';
                   $tags_out = explode(',',$line["tags"]);
                   for ($i=0;$i<count($tags_out);$i++) {
                       echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;tag='.trim($tags_out[$i]).'" title="Показать новости с меткой '.$tags_out[$i].'.">'.$tags_out[$i].'</a> ';
                    }
                 echo '<br />';
                   $query = "SELECT count(*) FROM comments WHERE articleid=".intval($line["id"]);
                   $result1 = mysql_query($query, $link);
                   while ($line1 = mysql_fetch_row($result1)) {
                         echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">Комментариев ('.$line1[0].')</a>';
                   }
                   
                 echo'</div>';
           }
       } 
       else {
                 $approved = 0;
                 echo '<br /><span style="color:red;">Нет такой новости или она ещё не проверена.</span><br /><br />';
       }
echo '<span>Комментарии посетителей:</span>';

  $query = "SELECT * FROM comments WHERE articleid=".intval($_GET['artid'])." ORDER BY commentid ASC";
  $result = mysql_query($query, $link);
    while ($line = mysql_fetch_row($result)) {

          echo '<div><div style="float:top;">';
          echo '<span style="color:blue;">'.$line[1].'<span style="font-size:70%;"> '.$line[5].' написал...</span>';
          echo '</span>';
          echo '</div>';
          echo '<span>'.comment_bbcode($line[2]).'</span>';
          echo '</div><br />';
    }

echo '<div id="comments_out"></div>';

   if ($state != 1) {
      echo '<br />
      <span style="color:red;">Зарегистрируйтесь, чтобы оставлять комментарии.</span><br /><br />';

   }
   
   if (($state == 1) && ($approved == 1)) {
      echo '<span>Добавить новый комментарий:</span><br />
      <form id="frmcomment" method="GET" action="">
	<span>Комментарий: </span><span style="color:red;">*</span><br />
	<textarea name="user_comment" style="width:600px;height:100px;"></textarea><br />
	<input type="hidden" name="article_id" value="'.intval($_GET['artid']).'" />
	<input type="submit" name="submit_reg_comment" value="Добавить комментарий" />
      </form>';

   }else {
      echo '<span>Добавить новый комментарий:</span><br /><br />
        <span>Поддерживается bbcode: <strong>[b], [i], [u]</strong>;</span><br/ >
        <form id="frmcomment" method="POST" action="">
           <span>Ник: </span><input type="text" name="user_name" value="anonymous" /><br />
           <span>Пароль: </span><input type="password" name="user_pass" value="aaaaaa" /><br />
           <span>Комментарий: </span><br />
           <textarea name="user_comment" style="width:600px;height:100px;"></textarea><br />
           <input type="hidden" name="article_id" value="'.intval($_GET['artid']).'" />
           <input type="hidden" name="td_post" value="" />
           <span>Введите код c картинки в поле ниже:</span><br>
           <input id="cfiled" type="text" name="cfiled" value="" /><img src="captcha.php"><span id="spanfiled" name="spanfiled"></span><br />
           <input type="submit" name="submit_comment" value="Добавить комментарий" />	
        </form>';
   }
  } elseif (isset($_GET['tag'])) {
          if (preg_match('/^[a-z0-9]{2,15}$/i',$_GET['tag'])) {
             echo '<strong>'.$_GET['tag'].'</strong><p>';
             $query = "SELECT * FROM `mynews` WHERE tags LIKE '%".$_GET['tag']."%' ORDER BY id DESC";
             $result = mysql_query($query, $link);
              while ($line = mysql_fetch_array($result)){
                 echo '<div class="sidebar"><div style="float:top;">';
                 echo '<span style="color:rgb(237, 106, 52);">'.$line["n_author"].' | <a style="color:blue;" href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">'.$line["title"].'</a></span><br /><span style="font-size:70%;">'.$line["n_time"].'</span>';
                 echo '</div><p>';
                 $exploded = explode('----',bbcode($line["newstext"]));///////////////////////////////////////////////////////
                 if ($exploded[1] == '') {
                 echo '<span>'.$exploded[0].'</span>';
                 } else {
                 echo '<span>'.$exploded[0].'<a style="float:right;" href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">Читать далее...</a></span>';
                 }
                 echo '</p>';
                 echo 'Метки: ';
                   $tags_out = explode(',',$line["tags"]);
                   for ($i=0;$i<count($tags_out);$i++) {
                       echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;tag='.trim($tags_out[$i]).'" title="Показать новости с меткой '.$tags_out[$i].'.">'.$tags_out[$i].'</a> ';
                    }
                   $query = "SELECT count(*) FROM comments WHERE articleid=".intval($line["id"]);
                   $result1 = mysql_query($query, $link);
                   while ($line1 = mysql_fetch_row($result1)) {
                         echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">Комментариев ('.$line1[0].')</a>';
                   }
                 echo'</div>';
             }
             echo '</p>';
          }
          //unset($_GET["tags"]);
   } else {
   $per_page = 10;
   if (isset($_GET['block'])) $page1 = ($_GET['block']-1); else $page1 = 0;
   // вычисляем первый оператор для LIMIT
   $start = abs($page1*$per_page);

   $query = "SELECT count(*) FROM `mynews`";
   $result = mysql_query($query, $link);
   $row = mysql_fetch_row($result);
   $total_rows = $row[0];
   $num_pages = ceil($total_rows/$per_page);



   //echo '<td style="vertical-align: top; width: 100%">'.$line[2]."\n".'<a href="news.php?artid='.$line[0].'">[..]</a><br />';
   //$query = "SELECT * FROM mynews WHERE approved='1' ORDER BY id DESC";
   $query="SELECT * FROM `mynews` WHERE approved='1' ORDER BY id DESC LIMIT ".$start.",".$per_page;
   $result = mysql_query($query, $link);
   while ($line = mysql_fetch_array($result)){
   //while ($line = mysql_fetch_row($result)) {
//mynews (id int(4) primary key auto_increment, title varchar(100), newstext TEXT, tags , n_time datetime, n_author varchar(20))";
                 echo '<div class="sidebar"><div style="float:top;">';
                 echo '<span style="color:rgb(237, 106, 52);">'.$line["n_author"].' | <a style="color:blue;" href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">'.$line["title"].'</a></span><br /><span style="font-size:70%;">'.$line["n_time"].'</span>';
                 echo '</div><p>';
                 $exploded = explode('----',bbcode($line["newstext"]));///////////////////////////////////////////////////////
                 if ($exploded[1] == '') {
                 echo '<span>'.$exploded[0].'</span>';
                 } else {
                 echo '<span>'.$exploded[0].'<a style="float:right;" href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">Читать далее...</a></span>';
                 }
                 echo '</p>';
                 echo 'Метки: ';
                   $tags_out = explode(',',$line["tags"]);
                   for ($i=0;$i<count($tags_out);$i++) {
                       echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;tag='.trim($tags_out[$i]).'" title="Показать новости с меткой '.$tags_out[$i].'.">'.$tags_out[$i].'</a> ';
                    }
                   $query = "SELECT count(*) FROM comments WHERE articleid=".intval($line["id"]);
                   $result1 = mysql_query($query, $link);
                   while ($line1 = mysql_fetch_row($result1)) {
                         echo '<a href="'.$_SERVER['PHP_SELF'].'?page=main&amp;artid='.$line[0].'">Комментариев ('.$line1[0].')</a>';
                   }
                   
                 echo'</div>';
   }
   
   for ($i=1;$i<=$num_pages;$i++) {
       if ($i-1 == $page1) {
          echo $i." ";
       } else {
          echo '<a href="'.$_SERVER['PHP_SELF'].'?block='.$i.'">'.$i."</a> ";
       }
   }
   echo '<br />';
}

   mysql_close($link);  
?>
  <!--div style="width:100%;text-align:center;"><span><a href="addnews.php">Добавить новость.</a></span>
  </div-->
  <br />

